package com.tencent.yolov8ncnn;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;



public class MainActivity extends Activity implements SurfaceHolder.Callback {
    public static final int REQUEST_CAMERA = 100;
    public static final int REQUEST_FOLDER_PERMISSION = 101;
    public static final int REQUEST_SELECT_FOLDER = 102;
    public static final int REQUEST_WRITE_STORAGE = 103;

    private Yolov8Ncnn yolov8ncnn = new Yolov8Ncnn();
    private int facing = 0;

    private Spinner spinnerModel;
    private Spinner spinnerCPUGPU;
    private int current_model = 0;
    private int current_cpugpu = 0;

    private SurfaceView cameraView;
    private Button folderButton;
    private Button processButton;
    private Button saveButton;
    private Button buttonSwitchCamera;

    private String selectedFolderPath = "";
    private File outputFolder;
    private List<String> imagePaths = new ArrayList<>();
    private int currentImageIndex = 0;

    private String outputFolderPath;

    /** Called when the activity is first created. */


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // 初始化SurfaceView
        cameraView = (SurfaceView) findViewById(R.id.cameraview);
        cameraView.getHolder().setFormat(PixelFormat.RGBA_8888);
        cameraView.getHolder().addCallback(this);

        // 初始化文件夹选择按钮
        folderButton = (Button) findViewById(R.id.buttonSelectFolder);
        folderButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestFolderPermission();
            }
        });

        folderButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.d("AssetImageLoader", "创建输出文件夹");
                // 确保输出文件夹存在
                createOutputFolder();

                Log.d("AssetImageLoader", "创建输出文件夹完毕！开始加载模型");

                reload();

                Log.d("AssetImageLoader", "创建输出文件夹完毕！开始检测图片！");

                // 直接加载 assets 中的图片
                AssetImageLoader.loadImages(MainActivity.this, yolov8ncnn, outputFolder);

                folderButton.setText("内置图片处理中");
                Toast.makeText(MainActivity.this, "开始处理内置图片！", Toast.LENGTH_SHORT).show();
            }
        });

        // 初始化处理按钮
        processButton = (Button) findViewById(R.id.buttonProcess);
        processButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (selectedFolderPath.isEmpty()) {

                    Toast.makeText(MainActivity.this, "请先选择文件夹", Toast.LENGTH_SHORT).show();
                    return;
                }

//                AssetImageLoader.loadImages(MainActivity.this, yolov8ncnn, outputFolder);
//                loadImagesFromFolder();
//                processNextImage();
            }
        });

        // 初始化保存按钮
        saveButton = (Button) findViewById(R.id.buttonSave);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (outputFolder == null) {
                    createOutputFolder();
                }
//                saveCurrentImage();
            }
        });

        // 初始化切换摄像头按钮
        buttonSwitchCamera = (Button) findViewById(R.id.buttonSwitchCamera);
        buttonSwitchCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                int new_facing = 1 - facing;
                yolov8ncnn.closeCamera();
                yolov8ncnn.openCamera(new_facing);
                facing = new_facing;
            }
        });

        // 初始化模型选择Spinner
        spinnerModel = (Spinner) findViewById(R.id.spinnerModel);
        ArrayAdapter<CharSequence> modelAdapter = ArrayAdapter.createFromResource(
                this, R.array.model_types, android.R.layout.simple_spinner_item);
        modelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerModel.setAdapter(modelAdapter);
        spinnerModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != current_model) {
                    current_model = position;
                    reload();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        // 初始化CPU/GPU选择Spinner
        spinnerCPUGPU = (Spinner) findViewById(R.id.spinnerCPUGPU);
        ArrayAdapter<CharSequence> cpugpuAdapter = ArrayAdapter.createFromResource(
                this, R.array.cpugpu_options, android.R.layout.simple_spinner_item);
        cpugpuAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCPUGPU.setAdapter(cpugpuAdapter);
        spinnerCPUGPU.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != current_cpugpu) {
                    current_cpugpu = position;
                    reload();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        // 默认选择第一个选项
        spinnerModel.setSelection(0);
        spinnerCPUGPU.setSelection(0);
        reload();
    }

    private void reload() {
        boolean ret_init = yolov8ncnn.loadModel(getAssets(), current_model, current_cpugpu);
        if (!ret_init) {
            Log.e("MainActivity", "yolov8ncnn loadModel failed");
            Toast.makeText(this, "模型加载失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        yolov8ncnn.setOutputWindow(holder.getSurface());
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {}

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {}

    @Override
    public void onResume() {
        super.onResume();
        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA);
        }
        yolov8ncnn.openCamera(facing);
    }

    @Override
    public void onPause() {
        super.onPause();
        yolov8ncnn.closeCamera();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CAMERA) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                yolov8ncnn.openCamera(facing);
            } else {
                Toast.makeText(this, "需要相机权限才能使用摄像头", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == REQUEST_FOLDER_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                selectFolder();
                openFolderSelector();
            } else {
                Toast.makeText(this, "需要存储权限才能选择文件夹", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == REQUEST_WRITE_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (outputFolder == null) {
                    createOutputFolder();
                }
            } else {
                Toast.makeText(this, "需要存储权限才能保存图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void requestFolderPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请存储权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_FOLDER_PERMISSION);
        } else {
            // 权限已获取，直接打开文件夹选择器
            openFolderSelector();
        }
    }

    // 打开文件夹选择器（需要集成第三方库或使用系统文件选择器）
    private void openFolderSelector() {
        // 方法1: 使用系统文件选择器 (Android 11+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            startActivityForResult(intent, REQUEST_SELECT_FOLDER);
        }
        // 方法2: 使用传统方式 (Android 10及以下)
        else {
            selectedFolderPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
            folderButton.setText("已选择: " + new File(selectedFolderPath).getName());
            Toast.makeText(this, "已选择图片文件夹: " + selectedFolderPath, Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELECT_FOLDER && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                Uri treeUri = data.getData();
                // 处理选择的文件夹URI
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    // 持久化URI权限
                    try {
                        getContentResolver().takePersistableUriPermission(treeUri,
                                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        // 将URI转换为路径
                        selectedFolderPath = uriToPath(treeUri);
                    } catch (SecurityException e) {
                        Log.e("MainActivity", "获取URI权限失败", e);
                        Toast.makeText(this, "文件夹访问权限获取失败", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    // 传统方法获取路径（Android 10及以下）
                    selectedFolderPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
                }

                if (!selectedFolderPath.isEmpty()) {
                    folderButton.setText("已选择: " + new File(selectedFolderPath).getName());
                    Toast.makeText(this, "已选择图片文件夹: " + selectedFolderPath, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "文件夹选择失败", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "未选择任何文件夹", Toast.LENGTH_SHORT).show();
            }
        }
    }

     // 将URI转换为路径的辅助方法
    private String uriToPath(Uri uri) {
        // 实际项目中需要完整实现此方法
        // 以下为简化示例
        if (uri == null) return "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+ 使用URI访问
            return ""; // 实际应返回合适的路径表示
        } else {
            // 传统方法获取路径
            String path = "";
            // 使用ContentResolver获取路径
            return path;
        }
    }

//    private void selectFolder() {
//        // 实际项目中应使用文件选择器库，此处为简化示例
//        selectedFolderPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
//        folderButton.setText("已选择: " + new File(selectedFolderPath).getName());
//        Toast.makeText(this, "已选择图片文件夹: " + selectedFolderPath, Toast.LENGTH_SHORT).show();
//    }

//    private void loadImagesFromFolder() {
//        imagePaths.clear();
//        File folder = new File(selectedFolderPath);
//        if (folder.exists() && folder.isDirectory()) {
//            File[] files = folder.listFiles();
//            if (files != null) {
//                for (File file : files) {
//                    String path = file.getAbsolutePath();
//                    if (path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".png")) {
//                        imagePaths.add(path);
//                    }
//                }
//            }
//        }
//        if (imagePaths.isEmpty()) {
//            Toast.makeText(this, "文件夹中没有找到图片", Toast.LENGTH_SHORT).show();
//        } else {
//            Toast.makeText(this, "找到 " + imagePaths.size() + " 张图片", Toast.LENGTH_SHORT).show();
//            currentImageIndex = 0;
//        }
//    }

//    private void processNextImage() {
//        if (imagePaths.isEmpty() || currentImageIndex >= imagePaths.size()) {
//            Toast.makeText(this, "所有图片处理完成", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        String imagePath = imagePaths.get(currentImageIndex);
//        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
//        if (bitmap != null) {
//            // 处理图片并显示结果
//            yolov8ncnn.processImage(bitmap);
//            currentImageIndex++;
//            Toast.makeText(this, "正在处理: " + new File(imagePath).getName(), Toast.LENGTH_SHORT).show();
//        } else {
//            currentImageIndex++;
//            processNextImage();
//        }
//    }

//    private void saveCurrentImage() {
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_STORAGE);
//            return;
//        }
//        if (outputFolder == null) {
//            createOutputFolder();
//        }
//        if (currentImageIndex > 0) {
//            String inputPath = imagePaths.get(currentImageIndex - 1);
//            File inputFile = new File(inputPath);
//            String outputFileName = "detected_" + inputFile.getName();
//            File outputFile = new File(outputFolder, outputFileName);
//            try {
//                FileOutputStream fos = new FileOutputStream(outputFile);
//                Bitmap processedBitmap = yolov8ncnn.getProcessedImage();
//                if (processedBitmap != null) {
//                    processedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
//                    fos.close();
//                    Toast.makeText(this, "图片已保存至: " + outputFile.getPath(), Toast.LENGTH_SHORT).show();
//                } else {
//                    Toast.makeText(this, "没有可保存的处理结果", Toast.LENGTH_SHORT).show();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//                Toast.makeText(this, "保存图片失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        } else {
//            Toast.makeText(this, "没有处理过的图片", Toast.LENGTH_SHORT).show();
//        }
//    }

    private void createOutputFolder() {
        outputFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "YOLOv8_Results");
        if (!outputFolder.exists()) {
            outputFolder.mkdirs();
        }

        outputFolderPath = outputFolder.getAbsolutePath();
        yolov8ncnn.setSavePath(outputFolderPath);

        // 在文件夹中创建README文件说明内容
        File readme = new File(outputFolder, "README.txt");
        try (FileOutputStream fos = new FileOutputStream(readme)) {
            String content = "此文件夹包含YOLOv8的检测结果：\n" +
                    "1. detected_*.jpg - 检测后的图片\n" +
                    "2. result_*.txt - 包含检测类别和置信度的文本文件";
            fos.write(content.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}

